import { useContext, useEffect, useMemo, useRef, useState } from 'react';
import { ContractManageAPI } from '../common/type';
import {
  AllBtnsConfig,
  editModifyContract,
  handListMoment,
  invalidModalOnOk,
  renderTipName,
  useOfdWord,
  handSupplierNames,
  handContractNodeList,
} from '../mconfig';
import { ConractControllerContext } from '../common';
import { Button, Space, message, Modal } from 'antd';
import {
  CheckCircleOutlined,
  ArrowRightOutlined,
  FileExclamationOutlined,
  FileExcelOutlined,
  UploadOutlined,
  FileTextOutlined,
  RollbackOutlined,
  StopOutlined,
  QuestionCircleOutlined,
  WarningOutlined,
} from '@ant-design/icons';
import moment from 'moment';
import { WorkflowChedkRecord, WorkflowHndTaskBtn, WorkflowNoDefaultTable, WorkflowSwitchModal } from '@/components/WorkflowCommonCopy';
import { changeNumMoneyToChinese, getTenantID, getPosIDs } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { ContractSignModal } from './ContractSignModal';
// import { StampContractModal } from './StampContractModal';
import { TipsErrorModalNew } from '@/components/TipsErrorModalNew';
import { invalidContractService } from '../services';
import { CancelModal } from '@/components/CancelModal';
import { getBaseUrl } from '@/services/urlconst';
import { getPersonalInfo } from '@/utils/authority';
import { history } from 'umi';

export const DetailInfoViewBottomBtn: React.FC<ContractManageAPI.IDetailInfoViewBottomBtn> = ({ position }) => {
  /** 申请页ref */
  const tipErrorModalRef: any = useRef();
  const { confirm } = Modal;

  /** 引入上下文 */
  const {
    curRes,
    pageType,
    contractDetailInfo,
    contractForm,
    oldContractInfo,
    contarctJsonList,
    reloadDetail,
    updteAddOrEdit,
    counterpartRows,
    locationState,
  } = useContext(ConractControllerContext);

  /** 是否统一文本变化 */
  const [isUnifiedText, setIsUnifiedText] = useState<boolean>(false);

  useEffect(() => {
    if (contractDetailInfo?.id) {
      setIsUnifiedText(contractDetailInfo?.templateFlag == 0 ? false : true);
    }
  }, [contractDetailInfo?.templateFlag]);

  // 审批记录渲染控制
  const [isShowAuditRecord, setIsShowAuditRecord] = useState<boolean>(false);

  /** 保存变更合同ID */
  const [modifyInfoDetail, setModifyInfoDetail] = useState<Record<string, any>>({});

  /** 是否打开切换流程组件 */
  const [showSwitchFlow, setShowSwitchFlow] = useState<boolean>(false);

  /** 点击按钮保存数据和弹框控制 */
  const [workFlowInfoObj, setWorkFlowInfoObj] = useState<Record<string, any>>({
    showWorkFlowModal: false,
    saveNoDefaultFlowID: '',
    workFlowNameStr: '',
  });

  /**
   * 关闭切换流程modal方法
   * @isDefaultModal  点击确定 true,关闭切换流程zujian,打开发起流程组件  点击取消 false 关闭切换流程组件
   */
  const closeSwitchFlowModal = (isDefaultModal: boolean) => {
    if (isDefaultModal) {
      setWorkFlowInfoObj({
        ...workFlowInfoObj,
        showWorkFlowModal: true,
      });
    } else {
      setShowSwitchFlow(false);
    }
  };

  /** 是否打开支付弹框 */
  const [openSignModalObj, setOpenSiginModalObj] = useState<Record<string, any>>({
    isShowModal: false,
    selectRow: {},
  });

  /** 电子签章 */
  // const [stampTipInfoModal, setStampTipInfoModal] = useState<Record<string, any>>({
  //   checkRowObj: {},
  //   showStampodal: false,
  // });

  /** 作废 */
  const [openCancelModal, setOpenCancelModal] = useState<Record<string, any>>({
    openModal: false,
    selectRows: {},
  });

  /** 签发提示框 */
  const [openTipInfoModal, setOpenTipInfoModal] = useState<Record<string, any>>({
    checkRowObj: {},
    showModal: false,
    tipType: null, // delete:删除   revoke:撤销
  });

  /** 按钮是否显示 */
  const allBtnsMemo = useMemo(() => {
    return AllBtnsConfig(curRes, contractDetailInfo, isUnifiedText, contractForm, oldContractInfo, pageType);
  }, [curRes, contractDetailInfo, isUnifiedText, contractForm, oldContractInfo, pageType]);

  /** 初始化数据 */
  useEffect(() => {
    if (contractDetailInfo && contractDetailInfo?.id) {
      const newDetailInfo: Record<string, any> = {
        ...contractDetailInfo,
        contractName: contractDetailInfo?.contractName,
        preBeginTime: contractDetailInfo?.preBeginTime ? moment(contractDetailInfo?.preBeginTime) : null,
        bidTime: contractDetailInfo?.bidTime ? moment(contractDetailInfo?.bidTime) : null,
        preFinishTime: contractDetailInfo?.preFinishTime ? moment(contractDetailInfo?.preFinishTime) : null,
        realBeginTime: contractDetailInfo?.realBeginTime ? moment(contractDetailInfo?.realBeginTime) : null,
        realFinishTime: contractDetailInfo?.realFinishTime ? moment(contractDetailInfo?.realFinishTime) : null,
        detailList: contractDetailInfo?.detailList?.length > 0 ? handListMoment(contractDetailInfo?.detailList, ['deliveryTime'], false) : [],
        processList: contractDetailInfo?.processList?.length > 0 ? handListMoment(contractDetailInfo?.processList, ['payTime'], false) : [],
        tempContractURL: contractDetailInfo?.tempContractURL,
        contractURL: contractDetailInfo?.contractURL,
        sumInTaxCN: contractDetailInfo?.sumInTax ? changeNumMoneyToChinese(contractDetailInfo?.sumInTax) : '零',
      };
      contractForm?.setFieldsValue({
        ...newDetailInfo,
      });
    }
  }, [contractDetailInfo?.id]);

  /** 签发按钮关闭 */
  const tipOnClose = () => {
    setOpenTipInfoModal({
      checkRowObj: {},
      showModal: false,
      tipType: null,
    });
  };

  /** 提示弹框回调 */
  const tipModalCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      reloadDetail();
      tipOnClose();
    } else {
      message.error(res?.msg);
    }
  };

  /** 引入撤销接口 */
  const { invalidContractRun } = invalidContractService(tipModalCallback);

  /** 点击编辑变更解除方法 */
  editModifyContract(modifyInfoDetail, setModifyInfoDetail);

  /** 处理转换文件 */
  const { onPrentOFD } = useOfdWord(contractDetailInfo, reloadDetail, () => {});

  /**保存前判断  若为补录添加提示信息 */
  const isSave = () => {
    confirm({
      title: '请仔细检查并确认补录的信息完整无误，保存后将无法修改!',
      icon: <WarningOutlined />,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        onSave();
      },
      onCancel() {},
    });
  };

  /** 提交补录合同 */
  const onSave = () => {
    contractForm?.validateFields()?.then((values: any) => {
      const payload: Record<string, any> = {
        ...values,
        ...contractDetailInfo,
        preBeginTime: values?.preBeginTime ? moment(values?.preBeginTime)?.format('YYYY-MM-DD HH:mm:ss') : null,
        preFinishTime: values?.preFinishTime ? moment(values?.preFinishTime)?.format('YYYY-MM-DD HH:mm:ss') : null,
        realBeginTime: values?.realBeginTime ? moment(values?.realBeginTime)?.format('YYYY-MM-DD HH:mm:ss') : null,
        realFinishTime: values?.realFinishTime ? moment(values?.realFinishTime)?.format('YYYY-MM-DD HH:mm:ss') : null,
        contractCode: values?.contractCode ? values?.contractCode : values?.draftCode,
        // detailList: values?.detailList?.length > 0 ? handListMoment(values?.detailList, ['deliveryTime'], true) : [],
        detailList:
          contarctJsonList?.detailList?.length > 0
            ? handListMoment(contarctJsonList?.detailList, ['deliveryTime'], true)
            : values?.detailList?.length > 0
            ? handListMoment(values?.detailList, ['deliveryTime'], true)
            : [],

        processList:
          contarctJsonList?.processList?.length > 0
            ? handListMoment(contarctJsonList?.processList, ['payTime'], true)
            : values?.processList?.length > 0
            ? handListMoment(values?.processList, ['payTime'], true)
            : [],
        bidTime: values?.bidTime ? moment(values?.bidTime)?.format('YYYY-MM-DD HH:mm:ss') : null,
        orderType: `${getTenantID()}${ILoadMapTypeAll.ALLORDER_TYPE}1020`,
        oppositeList: contarctJsonList?.oppositeList?.length > 0 ? contarctJsonList?.oppositeList : [],
        supplierName: counterpartRows?.length > 0 ? handSupplierNames(counterpartRows) : contractDetailInfo?.supplierName,
        // sumResidue: values?.sumInTax - values?.sumPaid ? values?.sumInTax - values?.sumPaid : 0,
        busiFlag: values?.busiDepartmentID ? 1 : 0,
        procureOrg: values?.procureOrg ? values?.procureOrg : `${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}1001`, //默认选择实验室集中采购
        procureReal: values?.procureReal ? values?.procureReal : `${getTenantID()}${ILoadMapTypeAll.PURCHASE_METHOD}1022`, //默认直接采购
      };
      delete payload['oldPreBeginTime'];
      delete payload['oldPreFinishTime'];

      if (contractDetailInfo?.id && contractDetailInfo.recordFlag == 1) {
        /** 处理支付数据 */
        const payProceList: Record<string, any>[] =
          contarctJsonList?.processList?.length > 0 ? handContractNodeList(contarctJsonList?.processList, values) : [];

        const editPayload: Record<string, any> = {
          ...contractDetailInfo,
          ...payload,
          ...contarctJsonList,
          id: contractDetailInfo?.id,
          state: contractDetailInfo?.state,
          detailList: contarctJsonList?.detailList?.length > 0 ? handListMoment(contarctJsonList?.detailList, ['deliveryTime'], true) : [],
          processList: handListMoment(payProceList, ['payTime'], true),
          versionNum: contractDetailInfo?.versionNum,
          oppositeList: contarctJsonList?.oppositeList?.length > 0 ? contarctJsonList?.oppositeList : [],
          attachList: contarctJsonList?.attachList?.length > 0 ? contarctJsonList?.attachList : [],
          sealURL: null,
          sumResidue: contractDetailInfo.sumResidue,
          sumInTax: contractDetailInfo.sumInTax,
        };
        delete editPayload['paramObject'];

        if (editPayload.recordFlag == 1) {
          editPayload['scanURL'] = editPayload?.contractURL;
          editPayload['sealURL'] = editPayload?.contractURL;
          editPayload['preBeginTime'] = editPayload?.realBeginTime;
          editPayload['preFinishTime'] = editPayload?.realFinishTime;

          //补录合同提交
          editPayload.state = `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}1004`;
          updteAddOrEdit.submitRecordContractRun(editPayload);
        }
      }
    });
  };

  const closeCurrent = () => {
    confirm({
      title: '关闭',
      icon: <QuestionCircleOutlined />,
      content: '确定要关闭当前页吗？',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        history.push({
          pathname: locationState?.returnPathName || '/contractController/homePage',
          state: {
            delRouterNameSource: history.location.pathname, //必传,要删除的路由名称
            returnPathName: locationState?.returnPathName,
          },
        });
      },
      onCancel() {},
    });
  };

  return (
    <>
      {allBtnsMemo?.allBtnDiv && (
        <div className="tabsBodyBottomBtn">
          <Space>
            {allBtnsMemo?.applyBtnDiv && (
              <Button
                type={'primary'}
                // icon={<CheckCircleOutlined />}
                onClick={() => {
                  if (contractDetailInfo.recordFlag == 1) {
                    //提交补录合同
                    isSave();
                  } else {
                    setWorkFlowInfoObj({
                      showWorkFlowModal: true,
                      saveNoDefaultFlowID: '',
                    });
                  }
                }}
              >
                {contractDetailInfo.recordFlag == 1 ? '保存' : '提交'}
              </Button>
            )}

            {/* {allBtnsMemo?.nextBtnDiv && (
              <Button
                type={'primary'}
                icon={<ArrowRightOutlined />}
                onClick={() => {
                  const formObj: Record<string, any> = contractForm?.getFieldsValue();
                  if (formObj && formObj?.templateURL) {
                    delete formObj['processList'];
                    delete formObj['detailList'];
                    delete formObj['attachList'];
                  } else {
                    message.warning('请选择合同范本！');
                  }
                }}
              >
                合同正文
              </Button>
            )} */}

            {allBtnsMemo?.signBtnDiv && position == 'top' && (
              <Button
                type={'primary'}
                // icon={<UploadOutlined />}
                onClick={() => {
                  setOpenSiginModalObj({
                    isShowModal: true,
                    selectRow: contractDetailInfo,
                  });
                }}
              >
                扫描件
              </Button>
            )}

            {allBtnsMemo?.printBtnDiv && position == 'top' && (
              <Button
                type="primary"
                // icon={<FileTextOutlined />}
                onClick={() => {
                  onPrentOFD(`${getBaseUrl()}${contractDetailInfo?.sealURL}`, 'print', contractDetailInfo, () => {});
                }}
              >
                打印
              </Button>
            )}

            {/* {allBtnsMemo?.signBtnDiv && (
              <Button
                type="primary"
                icon={<FileTextOutlined />}
                onClick={() => {
                  setStampTipInfoModal({
                    checkRowObj: contractDetailInfo,
                    showStampodal: true,
                  });
                }}
              >
                签章
              </Button>
            )} */}

            {allBtnsMemo?.modifyBtnDiv && position == 'top' && (
              <Button
                // icon={<FileExclamationOutlined />}
                type="primary"
                danger
                onClick={() => {
                  setModifyInfoDetail({
                    ...contractDetailInfo,
                    clickModify: true,
                    changeWay: 0,
                  });
                }}
              >
                变更
              </Button>
            )}

            {allBtnsMemo?.breakBtnDiv && position == 'top' && (
              <Button
                // icon={<FileExcelOutlined />}
                type="primary"
                danger
                onClick={() => {
                  setModifyInfoDetail({
                    ...contractDetailInfo,
                    clickModify: true,
                    changeWay: 1,
                  });
                }}
              >
                解除
              </Button>
            )}

            {/* 流程节点弹框 */}
            {position == 'top' && (
              <WorkflowHndTaskBtn
                flowDetailInfo={allBtnsMemo?.flowHandList}
                reloadCallback={reloadDetail}
                requestController={'contractController'}
                detailInfoObj={contractDetailInfo}
                flowBusinessType={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1007`} // handHelpType={false}
              />
            )}

            {allBtnsMemo?.revokeBtnDiv && position == 'top' && (
              <Button
                type="primary"
                danger
                // icon={<RollbackOutlined />}
                onClick={() => {
                  setOpenTipInfoModal({
                    checkRowObj: contractDetailInfo,
                    showModal: true,
                    tipType: 'revoke',
                  });
                }}
              >
                撤销
              </Button>
            )}

            {/* {allBtnsMemo?.cancelBtnDiv && (
              <Button
                type="primary"
                danger
                icon={<StopOutlined />}
                onClick={() => {
                  setOpenCancelModal({
                    openModal: true,
                    selectRows: contractDetailInfo,
                  });
                }}
              >
                作废
              </Button>
            )} */}

            {allBtnsMemo?.cancelBtnDiv && position == 'top' && (
              <Button
                type="primary"
                danger
                // icon={<StopOutlined />}
                onClick={() => {
                  setWorkFlowInfoObj({
                    showWorkFlowModal: true,
                    saveNoDefaultFlowID: '',
                    workFlowNameStr: '合同作废',
                  });
                }}
              >
                作废
              </Button>
            )}
            <Button danger onClick={closeCurrent}>
              关闭
            </Button>
          </Space>
        </div>
      )}
      {!allBtnsMemo?.allBtnDiv && (
        <div className="tabsBodyBottomBtn">
          <Button danger onClick={closeCurrent}>
            关闭
          </Button>
        </div>
      )}
      {/* 审核记录 */}
      {contractDetailInfo?.id && contractDetailInfo?.paramObject && allBtnsMemo?.isShowCheckList && position == 'bottom' && (
        <WorkflowChedkRecord
          curRes={curRes}
          dataDetailInfo={contractDetailInfo}
          flowBusinessType={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1007`}
          requestController={'contractController'}
          reloadPageCallback={reloadDetail} // 刷新方法-详情方法
          revokeStateID={`${getTenantID()}${ILoadMapTypeAll?.CONTRACT_STATE}1000`}
          allBtnFuncQuqry={allBtnsMemo}
          tabPaneHeight={0.35}
          isCheckDrawer={true}
          isShowCollapse={isShowAuditRecord}
          changeCollapse={(val) => {
            setIsShowAuditRecord(val);
          }}
          cancelStateId={`${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}1007`}
          // isHiddenTabsTitle={true}
          exportPdfField={() => {}}
        />
      )}

      {/* 上传合同扫描件 */}
      {openSignModalObj?.isShowModal && (
        <ContractSignModal
          onClose={() => {
            setOpenSiginModalObj({
              isShowModal: false,
              selectRow: {},
            });
          }}
          selectRowInfo={openSignModalObj?.selectRow}
          reloadManage={reloadDetail}
        />
      )}

      {/* 提示框 */}
      {openTipInfoModal?.showModal && (
        <TipsErrorModalNew
          ref={tipErrorModalRef}
          modalLoading={false}
          onClose={tipOnClose}
          modalOnOK={
            openTipInfoModal?.tipType == 'revoke'
              ? () => {
                  invalidModalOnOk(openTipInfoModal?.checkRowObj, invalidContractRun);
                }
              : () => {}
          }
          tipTextColor="#000"
          modalTip={renderTipName(openTipInfoModal?.tipType, openTipInfoModal?.checkRowObj)}
        />
      )}

      {/* 作废弹框 */}
      {openCancelModal?.openModal && (
        <CancelModal
          onClose={() => {
            setOpenCancelModal({
              openModal: false,
              selectRows: {},
            });
          }}
          checkRows={openCancelModal?.selectRows}
          reloadManage={reloadDetail}
          modalTitle="合同作废"
          cancelRequestUrl="/contractController/cancel"
          cancelRequestType="PUT"
          cancelFormReasonRequired={true}
          cancelTypeDic={`${ILoadMapTypeAll.CONTRACT_CANCELTYPE}`}
          cancelRequestBody={{
            pID: openCancelModal?.selectRows?.pID,
            // workflowID: openCancelModal?.selectRows?.workflowID,
            orderType: openCancelModal?.selectRows?.orderType,
            // businessType: openCancelModal?.selectRows?.businessType,
            businessType: openCancelModal?.selectRows?.workflowType,
            state: `${getTenantID()}${ILoadMapTypeAll.CONTRACT_STATE}1007`,
          }}
        />
      )}

      {/* 发起流程审批 */}
      {workFlowInfoObj?.showWorkFlowModal && (
        <WorkflowSwitchModal
          openVisible={workFlowInfoObj?.showWorkFlowModal} //是否显示发起流程
          onClose={() => {
            //关闭弹框
            setWorkFlowInfoObj({
              ...workFlowInfoObj,
              showWorkFlowModal: false,
            });
          }}
          businessInfoObj={contractDetailInfo} //数据详情
          requestController="contractController" //业务
          orderType={contractDetailInfo?.orderType || `${getTenantID()}${ILoadMapTypeAll.ALLORDER_TYPE}1020`} //业务工单类别
          category={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1007`} //流程类别
          businessCategory={`${getTenantID()}${ILoadMapTypeAll.CONTRACT_FLOWTYPE}1000`} //业务流程类别
          reloadInfoCallback={reloadDetail} //刷新
          openFlowChangeModal={setShowSwitchFlow} //切换非默认流程
          selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID} //流程ID
          workFlowName={workFlowInfoObj?.workFlowNameStr} //流程名称
          procdefFlag={true}
        />
      )}

      {/* 挑选流程组件 */}
      {showSwitchFlow && (
        <WorkflowNoDefaultTable
          openVisibleSwitch={showSwitchFlow}
          onCloseSwitch={closeSwitchFlowModal}
          requestController="contractController"
          orderType={contractDetailInfo?.orderType || `${getTenantID()}${ILoadMapTypeAll.ALLORDER_TYPE}1020`}
          category={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1007`}
          businessCategory={`${getTenantID()}${ILoadMapTypeAll.CONTRACT_FLOWTYPE}1000`}
          saveSelectFlowID={(flowId: string) => {
            setWorkFlowInfoObj({
              ...workFlowInfoObj,
              saveNoDefaultFlowID: flowId,
            });
          }}
          selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
        />
      )}
    </>
  );
};
